package com.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.common.constant.Constant;
import com.common.utils.*;
import com.entity.Card;
import com.entity.Hint;
import com.entity.Node;
import com.entity.TaskRecord;
import com.mapper.NodeMapper;
import com.service.CardService;
import com.service.HintService;
import com.service.NodeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.service.TaskRecordService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wty
 * @since 2022-01-04
 */
@Service
public class NodeServiceImpl extends ServiceImpl<NodeMapper, Node> implements NodeService {

    @Autowired
    private CardService cardService;

    @Autowired
    private TaskRecordService taskRecordService;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private HintService hintService;

    @Override
    public Result getNode() {
        Wrapper<Node> wr=new EntityWrapper<>();
        List<Node> nodes = this.selectList(wr);

        List<Node> update=new ArrayList<>();

        Map<Integer,Node> nodeMap=new HashMap<>();
        for (Node node : nodes) {
            String cardId = node.getCardId();
            if(!StringUtil.isEmpty(cardId)){
                List<String> cardList = JSONArray.parseArray(cardId, String.class);
                //根据卡片Id查找卡片内容
                Wrapper<Card> cardwr=new EntityWrapper<>();
                cardwr.in("id",cardList);
                List<Card> cards = cardService.selectList(cardwr);
                node.setCardList(cards);

                //判断卡片是否减少
                if(cardList.size()!=cards.size()){
                    List<String> str=new ArrayList<>();
                    for (Card card : cards) {
                        str.add(card.getId().toString());
                    }
                    node.setCardId(JSONArray.toJSONString(str));
                    update.add(node);
                }
            }

            //根据node查询record
            Wrapper<TaskRecord> wrr=new EntityWrapper<>();
            wrr.eq("task_id",node.getId());
            //时间本月
            wrr.gt("add_time", DateUtil.getCurrentMonthFirstDay());
            List<TaskRecord> taskRecords = taskRecordService.selectList(wrr);
            node.setTaskRecords(taskRecords);
            if(!CollectionUtils.isEmpty(taskRecords)){
                List<Integer> dataList=new ArrayList<>();
                Map<String,TaskRecord> tmap=new HashMap<>();
                for (TaskRecord taskRecord : taskRecords) {
                    tmap.put(taskRecord.getAddTime(),taskRecord);
                    dataList.add(Integer.valueOf(taskRecord.getAddTime().substring(8)));
                }
                node.setDataList(dataList);
                node.setTaskRecordMap(tmap);
            }

            nodeMap.put(node.getId(),node);
        }

        List<Node>  reList=new ArrayList<>();
        for (Integer idKey : nodeMap.keySet()) {
            Node node = nodeMap.get(idKey);
            if(0!=node.getPid()){
                Node vo = nodeMap.get(node.getPid());
                List<Node> childNode = vo.getChildNode();
                childNode.add(node);
            }else{
                reList.add(node);
            }
        }
        return  Result.success(reList);
    }

    /**
     *
     */
    @Override
    public void send() {
//        Wrapper<Node> wr=new EntityWrapper<>();
//        List<Node> nodes = this.selectList(wr);
//
//        List<Node> yesLabes=new ArrayList<>();//处于当前时间范围内的标签
//        List<Node> noLabes=new ArrayList<>();//不处于当前时间范围内的标签
//        //判断现在的时间，把属于这个时间段的习惯筛选出来
//        String nowTime = DateFormatUtils.format(new Date(), "HHmm");//2018
//        String time1 = nowTime.substring(0,2);//现在几点
//        String time2 = nowTime.substring(2,4);//现在多少分
//        Integer index = Integer.valueOf(time1);
//
//        for (Node node : nodes) {
//            String executeTime = node.getExecuteTime();
//            //判断是否在范围内，
//            List<Integer> integers = JSONArray.parseArray(executeTime, Integer.class);
//            if(integers.get(index)==2){
//                    yesLabes.add(node);
//                }else{
//                    noLabes.add(node);
//           }
//        }
//
//        if(!CollectionUtils.isEmpty(yesLabes)){
//            for (Node yesLabe : yesLabes) {
//                //查询对应的卡片
//                String cardId = yesLabe.getCardId();
//                List<String> strings = JSONArray.parseArray(cardId, String.class);
//                Wrapper<Card> wrcard=new EntityWrapper<>();
//                wrcard.in("id",strings);
//                List<Card> cards = cardService.selectList(wrcard);
//                //随机抽几条
//                List<Card> cardList=new ArrayList<>();
//                if(!CollectionUtils.isEmpty(cards)){
//                    for (Card card : cards) {
//                        cardList.add(card);
//                    }
//                }else{
//                    continue;
//                }
//                //发送通知
//                Integer id = yesLabe.getId();
//                Long aLong = Constant.INFORM_MAP.get(id);
//                //判断状态，
//                //今天已经通知过一次
//                if(null!=aLong){
//                    Long longByCurrTime = DateUtil.getLongByCurrTime();
//                    if(longByCurrTime-aLong>60*60*24){
//                        //发送通知
//                        this.doSend(cardList,yesLabe);
//                        Constant.INFORM_MAP.put(id,DateUtil.getLongByCurrTime());
//                    }
//                }else{
//                        //发送通知
//                    this.doSend(cardList,yesLabe);
//                    Constant.INFORM_MAP.put(id,DateUtil.getLongByCurrTime());
//                }
//            }
//        }
    }

    /**
     * 随机选出一条进行通知
     * @param cardList
     * @param yesLabe
     */
    @Override
    public void doSend(List<Card> cardList,Node yesLabe) {
        Random random = new Random();
        int n = random.nextInt(cardList.size());
        Card card = cardList.get(n);
        sendDingDing(card.getContent(),yesLabe.getName());
        //https://oapi.dingtalk.com/robot/send?access_token=f98cb9a16d5192c2a604830299249281b5e4dc5a9a5fb6d79622fbb45fd007e1

    }

    /**
     * 添加节点
     * @param node
     * @return
     */
    @Override
    public Result addNode(Node node) {
        node.setExecuteTime("[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]");
        boolean insert = this.insert(node);
        if(insert){
            //添加提示时间
            Hint hint=new Hint();
            hint.setExecuteTime("[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]");
            hint.setTaskId(node.getId());
            hintService.insert(hint);
            return  Result.success("添加成功");
        }else{
            return  Result.error("添加失败");
        }
    }

    @Override
    public Result getNodeList() {
        Wrapper<Node> wr=new EntityWrapper<>();
        List<Node> nodes = this.selectList(wr);
        return Result.success(nodes);
    }

    private synchronized void sendDingDing(String sb, String title) {

        try {
            Thread.sleep(5000);
            //钉钉机器人地址（配置机器人的webhook）
            String dingUrl = "https://oapi.dingtalk.com/robot/send?access_token=f98cb9a16d5192c2a604830299249281b5e4dc5a9a5fb6d79622fbb45fd007e1";
            //是否通知所有人
            boolean isAtAll = true;
            //通知具体人的手机号码列表
            List<String> mobileList = new ArrayList<>();
            mobileList.add("18285152065");
            //组装请求内容
            String reqStr = buildReqStr(sb, isAtAll, mobileList,title+":"+sb);
            //推送消息（http请求）
            String result = HttpUtil.postJson(dingUrl, reqStr);
            System.out.println("result == " + result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static String buildReqStr(String sb, boolean isAtAll, List<String> mobileList,
                                      String title) {

        Map<String, Object> atMap =new HashMap<>();
        //1.是否通知所有人
        atMap.put("isAtAll", isAtAll);
        //2.通知具体人的手机号码列表
        atMap.put("atMobiles", mobileList);
        Boolean f=true;
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("msgtype", "markdown");
        Map<String,Object> pmap=new HashMap<>();
        pmap.put("text", ""+"["+"地址"+"](http://124.220.197.73:9981)"+title);
        pmap.put("title",""+title);
        reqMap.put("markdown", pmap);

        return JSON.toJSONString(reqMap);
    }

}
